package com.dfbz.controller;

import com.dfbz.entity.Dept;
import com.dfbz.entity.PageEntity;
import com.dfbz.entity.User;
import com.dfbz.service.UserService;
import com.dfbz.service.deptService;
import com.dfbz.utils.XBUtils;
import com.dfbz.utils.genrateYzm;
import org.apache.commons.beanutils.BeanUtils;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import static com.dfbz.controller.SendMailUtil.sendEmail;

@WebServlet("/user/*")
public class userServlet extends baseServlet {
    public UserService uservice = new UserService();
    public deptService deptservice = new deptService();

    /**
     * 检测邮箱
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void checkEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取前端传来的参数
        String email = request.getParameter("email");
        User user = uservice.findByEmail(email);
        if (user != null) {
            response.getWriter().write("1");
            return;
        } else {
            response.getWriter().write("0");
        }
    }

    /**
     * 检测用户名
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void checkUsername(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取前端传来的参数
        String username = request.getParameter("username");
        User user = uservice.findByUserName(username);
        if (user != null) {
            response.getWriter().write("1");
            return;
        } else {
            response.getWriter().write("0");
        }
    }

    /**
     * 注册
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws ServletException
     */
    public void register(HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException, ServletException {
        User user = new User();
        BeanUtils.populate(user, request.getParameterMap());
        uservice.save(user);
        response.sendRedirect("/index.jsp");
    }

    /**
     *
     */
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端传来的参数
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        String remeberMe = request.getParameter("remeberMe");
        //获取checkCODE生成的验证码
        String sessionCode = (String) session.getAttribute("sessionCode");
        if (!sessionCode.equals(checkCode)) {
            request.setAttribute("error", "验证码错误");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }
        User user = uservice.findByUserName(username);
        if (!user.getUsername().equals(username)) {
            request.setAttribute("error", "用户名错误");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }
        if (!user.getPassword().equals(password)) {
            request.setAttribute("error", "密码错误");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }
        //更改用户的登录时间
        UserService.updateLoginTime(user.getId());
        if (remeberMe != null) {
            //说明用户勾选了

            // 说明用户勾选了 '记住我'
            Cookie cookie = new Cookie("loginUser", user.getId() + "");

            // 设置cookie携带路径(整体项目都携带)
            cookie.setPath("/");

            // cookie过期时间
            cookie.setMaxAge(60 * 60 * 24 * 7);

            // 写回客户端
            response.addCookie(cookie);

        }

        session.setAttribute("loginUser", user);
        response.sendRedirect("/home/findAlldata");
    }


    /**
     * 分页+模糊查询
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws ServletException
     */

    public void findPage(HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException, ServletException {
        //查找当前页  ---->  模糊查询f
        Integer currPage = Integer.parseInt(getParam(request).get("currPage"));
        String realName = getParam(request).get("realName");
        PageEntity<User> userList = uservice.findPage(realName, currPage);
        //要在渲染所有用户之前判断该用户有没有被关注，如果是自己则不能关注
        List<Long> focusList = uservice.findFocusList(loginUser.getId());
        request.setAttribute("focusList", focusList);
        request.setAttribute("userList", userList);
        request.setAttribute("realName", realName);
        request.getRequestDispatcher("/html/user.jsp").forward(request, response);
    }

    /**
     * 关注 取消关注
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws ServletException
     */
    public void focus(HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException, ServletException {
        Map<String, String> param = getParam(request);
        Long userId = Long.parseLong(param.get("userId"));
        //用户加关注 1：表示关注  0 取消关注
        Integer flag = uservice.focus(loginUser.getId(), userId);
        writerObjToString(response, flag);
    }

    /**
     * 与后端 约定好。如果flag是detail则是查看自己信息  跳转到detail.jsp 否则跳转到look。jsp
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws ServletException
     */
    public void userDetail(HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException, ServletException {
        Map<String, String> param = getParam(request);
        //
        String flag = param.get("flag");
        long id = Long.parseLong(param.get("id"));
        //查找个人信息方便回显
        User user = uservice.findByid(id);
        //填充个人信息
        request.setAttribute("user", user);
        if ("detail".equals((param.get("flag")))) {

            // 代表是查看别人的
            // 查看数+1
            uservice.inLook(id);
            //查询粉丝数
            Integer fans = uservice.countFansByUserId(id);
            request.setAttribute("fans", fans);
            request.getRequestDispatcher("/html/user_detail.jsp").forward(request, response);
            return;
        } else {
            //代表是查看自己的
            Integer focus = uservice.countFoucsByUserId(id);
            //查询出全部的部门
            List<Dept> deptList = deptservice.findAlldept();
            request.setAttribute("deptList", deptList);
            request.setAttribute("focus", focus);
            request.getRequestDispatcher("/html/user_look.jsp").forward(request, response);
        }
    }

    /**
     * 图片上传类
     *
     * @param request
     * @param response
     * @throws Exception
     */

    public void updatePic(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 调用文件上传工具类
        String fileName = com.dfbz.xb.utils.FileUploadUtils.upload("/upload", request);

        String picUrl = "http://localhost:8080/upload/" + fileName;

        // 修改session中的pic地址
        loginUser.setPic(picUrl);

        // 修改数据库中的pic地址
//        UserService.updateUrl(loginUser.getId(), picUrl);
        UserService.updateUrl(loginUser.getId(), picUrl);

        // 将新的图片地址写到前端
        writerObjToString(response, picUrl);

    }

    public void update(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {

        Map<String, String> param = getParam(request);
        String realName = param.get("realName");
        String phone = param.get("phone");
        String gender = param.get("gender");
        String isSecret = param.get("isSecret");
        Long deptId = Long.parseLong(param.get("deptId"));
        Long age = Long.parseLong(param.get("age"));

        // 如果前端没有勾选私密 (我要公开)
        if (isSecret == "") {

            isSecret = "1";
        }

        loginUser.setRealName(realName);
        loginUser.setDeptId(deptId);
        loginUser.setPhone(phone);
        loginUser.setAge(age);
        loginUser.setGender(gender);
        loginUser.setIsSecret(isSecret);

        Dept dept = deptservice.findByID(deptId);
        loginUser.setDeptName(dept.getName());

        UserService.update(loginUser);


        //  重定向到userDetailServlet进行数据的查询
        response.sendRedirect("/user/userDetail?id=" + loginUser.getId());
    }

    /**
     * 我关注的用户分页
     *
     * @param request
     * @param response
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws IOException
     */

    public void findFocusPage(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException, ServletException {
        //获取前端参数
        Map<String, String> param = getParam(request);
        //获取当前页
        Integer currPage = Integer.parseInt(param.get("currPage"));
        PageEntity pageData = uservice.findFocusPage(currPage, loginUser.getId());
        request.setAttribute("currPage", currPage);
        request.setAttribute("pageData", pageData);
        request.getRequestDispatcher("/html/my_user.jsp").forward(request, response);
    }


    public void findUserByDeptId(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Long deptId = Long.parseLong(getParam(request).get("deptId"));

        List<Map<String, Object>> userMapList = UserService.findUserByDeptId(deptId);

        writerObjToString(response, userMapList);
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.getSession().removeAttribute("loginUser");

        Cookie loginCookie = XBUtils.getCookie(request, "loginUser");
        if (loginCookie != null) {
            // 销毁cookie
            loginCookie.setPath("/");
            loginCookie.setMaxAge(0);
            response.addCookie(loginCookie);
        }

        response.sendRedirect("/index.jsp");
    }

    /**
     *微信登陆处理回调
     * @param request
     * @param response
     * @throws Exception
     */
    public void wx_login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //加载配置文件
        Properties pro = new Properties();
        pro.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
        String appid = pro.getProperty("wx.AppID");
        //微信授权成功后的回调地址
        String redirect_uri = pro.getProperty("wx.redirect_uri");

        String url = "https://open.weixin.qq.com/connect/qrconnect?response_type=code"+
                "&appid=" + appid +
                "&redirect_uri=" + URLEncoder.encode(redirect_uri) +
                "&scope=snsapi_login";

        // 重定向到微信登录指定的地址进行微信登录授权,授权成功后返回code
        response.sendRedirect(url);

    }

    /**
     * 发送随机验证码 到邮箱，存到session，
     * @param request
     * @param response
     */
    public  void sendemail(HttpServletRequest request, HttpServletResponse response){
        /**
         * 前端获取邮箱，用户名随便
         * 调用 SendMailUtil sendEmail() 发送邮箱，
         * genrateYzm.sendYzm() 验证码，保存到 session
         */

        //前端输入框获取的邮箱
        String parameter = request.getParameter("email");
        try {
            String yzm = sendEmail(parameter, "mzp");
            HttpSession session = request.getSession();
            //session设置一个
            session.setAttribute("yzmNumber",yzm);
            //seession设置会话维持时间
            session.setMaxInactiveInterval(60);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
    //重置密码
    public void resist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端传来的参数
        Map<String, String> param = getParam(request);
        String email = param.get("email");
        String password = param.get("password");
        uservice.resist(password,email);
        response.sendRedirect("/index.jsp");
    }
}
